<?php

namespace app\common\model\xiservice;

use think\Model;
use think\Db;
use app\common\model\xiservice\Service;
use app\common\model\xiservice\User as XiserviceUser;
use think\Exception;

class Benfit extends Model
{


    // 表名
    protected $name = 'xiservice_user_benfit';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'service_info',
        'status_text',
        'createtime_text'
    ];


    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    public function getServiceInfoAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_id']) ? $data['order_id'] : 0);
        if ($value) {
            if ($data['type'] == 1 || $data['type'] == 2) {
                $order = Order::where('id', $value)->find();
                if (!$order) {
                    return [];
                }
                $service = Service::where('id', $order['service_id'])->field('id,name,image')->find();
                if (!$service) {
                    return [];
                }
                return $service;
            }
        }

        return [];
    }

    public function order()
    {
        return $this->belongsTo('app\common\model\xiservice\Order', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function unfreeze($data)
    {
        Db::startTrans();
        try {
            //更新解冻状态
            $res = $this->where('id', $data['id'])->update(['status' => 2]);
            //用户可提现金额增加
            $userinfo = XiserviceUser::where("user_id", $data['user_id'])->setInc("can_money", $data['money']);
            //用户冻结金额减少
            $userinfo = XiserviceUser::where("user_id", $data['user_id'])->setDec("freeze_money", $data['money']);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        }
        return ["status" => true, "data" => [], "msg" => 'success'];
    }
}
